<!DOCTYPE html>
<html>
<head>
<title>H Tree fractal</title>

<style type="text/css">body{margin:0;}canvas{background:#000;/*HACK: keep scrollbars from showing*/display:block;}</style>

<script type="text/javascript" src="paper.js"></script>

<script type="text/javascript">

var HTreeFractal = HTreeFractal || {};
var root2 = Math.sqrt(2);
var startLength = 500;
var minPathLength = 10;
var totalLength;



function foo() {
	var path = new Path.Line([view.center.x - startLength / 2, view.center.y], [view.center.x + startLength / 2, view.center.y]);

	totalLength = 0;

	for (var i = startLength; i >= minPathLength;  i /= Math.sqrt(2)) {
		totalLength += i;
	}

	totalLength = totalLength / 2;

	path.strokeColor = getStrokeColor(path.length, 0, path.segments[0].point, path.segments[1].point);

	bar(path);
}

function bar(p) {
	var newLength = 0;

	if ( (newLength = p.length / root2) < minPathLength) return;

	if (p.segments[0].point.x === p.segments[1].point.x) {  //p is vertical
		var l0 = new Path.Line([p.segments[0].point.x - newLength / 2, p.segments[0].point.y], [p.segments[0].point.x + newLength / 2, p.segments[0].point.y]);
		var l1 = new Path.Line([p.segments[1].point.x - newLength / 2, p.segments[1].point.y], [p.segments[1].point.x + newLength / 2, p.segments[1].point.y]);
	} else {  //p is horizontal
		var l0 = new Path.Line([p.segments[0].point.x, p.segments[0].point.y - newLength / 2], [p.segments[0].point.x, p.segments[0].point.y + newLength / 2]);
		var l1 = new Path.Line([p.segments[1].point.x, p.segments[1].point.y - newLength / 2], [p.segments[1].point.x, p.segments[1].point.y + newLength / 2]);
	}

	l0.strokeColor = getStrokeColor(l0.length, p.strokeColor.gradient.stops[0].color.hue, l0.segments[0].point, l0.segments[1].point);
	l1.strokeColor = getStrokeColor(l1.length, p.strokeColor.gradient.stops[0].color.hue, l1.segments[0].point, l1.segments[1].point);

	bar(l0);
	bar(l1);
}


function getStrokeColor(pathLength, startHue, origin, destination) {
	var c1 = new Color();
	var c2 = new Color();
	var colorSpan = 360 / totalLength * pathLength / 2;
	var offset = startHue;
	c1.lightness = c2.lightness = .5;
	c1.saturation = c2.saturation = 1;
	c1.hue = offset;
	c2.hue = offset + colorSpan;

	return {
		gradient: { stops: [c2, c1, c2] },
		origin : origin,
		destination : destination
	};
}


paper.install(window);


window.onload = function() {
	paper.setup('clock');

	view.onResize = function(event) { view.center = [0,0]; };
	view.onFrame = function(event) {  };

	foo();
}

</script>
</head>
<body>
	<canvas id="clock" data-paper-resize="true"></canvas>
</body>
</html>